package com.party.jackclientandroid.ui_home.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.party.jackclientandroid.R;
import com.party.jackclientandroid.Constant;
import com.party.jackclientandroid.api.CouponService;
import com.party.jackclientandroid.api.DefaultConsumer;
import com.party.jackclientandroid.BaseActivity;
import com.party.jackclientandroid.BaseFragment;
import com.party.jackclientandroid.bean.BaseResult;
import com.party.jackclientandroid.bean.SpellingGroupCouponBean;
import com.party.jackclientandroid.loadviewhelper.help.OnLoadViewListener;
import com.party.jackclientandroid.loadviewhelper.load.LoadViewHelper;
import com.party.jackclientandroid.ui_home.activity.SpellingGroupCouponDetailActivity;
import com.party.jackclientandroid.utils.TimeUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.iwgang.countdownview.CountdownView;
import io.reactivex.functions.Consumer;


public class SpellingGroupCouponChildFragment extends BaseFragment {

    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refresh_layout;
    @BindView(R.id.recycler_view)
    RecyclerView recycler_view;

    private CouponService couponService;
    private CommonAdapter<SpellingGroupCouponBean> commonAdapter;
    private List<SpellingGroupCouponBean> dataList = new ArrayList<>();
    private int currPage = 1;
    private boolean noMoreData = false;
    private int category_id = 0;

    public static SpellingGroupCouponChildFragment newInstance(int nearby_type_id) {
        SpellingGroupCouponChildFragment fragment = new SpellingGroupCouponChildFragment();
        Bundle args = new Bundle();
        args.putInt("category_id", nearby_type_id);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void receiveBundleFromActivity(Bundle arg) {
        category_id = arg.getInt("category_id");
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_spelling_group_coupon_child;
    }

    @Override
    protected void initData() {
        super.initData();
        couponService = new CouponService((BaseActivity) mActivity);
        helper = new LoadViewHelper(refresh_layout);
        helper.setListener(new OnLoadViewListener() {
            @Override
            public void onRetryClick() {
                loadData();
            }
        });
        initView();
        helper.showLoading();
        loadData();
    }

    public void initView(){
        refresh_layout.setEnableFooterFollowWhenLoadFinished(true);
        commonAdapter = new CommonAdapter<SpellingGroupCouponBean>(mActivity, R.layout.item_spelling_group_coupon, dataList) {
            @Override
            protected void convert(ViewHolder viewHolder,final SpellingGroupCouponBean item, int position) {
                viewHolder.setText(R.id.shop_name_tv,item.getShopName());
                mApplication.getImageLoaderFactory().loadCommonImgByUrl(mActivity,item.getGroupBuyImg(),(ImageView) viewHolder.getView(R.id.coupon_iv));
                viewHolder.setText(R.id.coupon_name_tv,item.getUnionStartNumber()+"至"+item.getUnionEndNumber()+"人"+item.getDinersNumberName());
                viewHolder.setText(R.id.num_person_spelling_group_price,item.getUnionStartNumber()+"-"+item.getUnionEndNumber()+"拼团价");
                viewHolder.setText(R.id.remain_count_tv,"还剩"+item.getStockCount()+"次");
                viewHolder.setText(R.id.buy_prce_tv,"¥"+item.getBuyPrice());
                viewHolder.setText(R.id.original_price_tv,"¥"+item.getOriginalPrice());
                viewHolder.setText(R.id.distance_tv,item.getSymbolBuild());
                viewHolder.setOnClickListener(R.id.now_rob_btn, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(mActivity, SpellingGroupCouponDetailActivity.class);
                        intent.putExtra("couponId",item.getId());
                        startActivity(intent);
                    }
                });
                //处理剩余时间
                CountdownView countdownView = viewHolder.getView(R.id.count_down_view);
                LinearLayout remain_time_ll = viewHolder.getView(R.id.remain_time_ll);
                TextView remain_time_tv = viewHolder.getView(R.id.remain_time_tv);
                long currTimeStamp = TimeUtil.getCurrTimeStamp();
                long endTimeStamp = item.getEndSaleTime();
                String result = TimeUtil.getDistanceTime(currTimeStamp,endTimeStamp);
                if(result.equals("不到一天")){
                    countdownView.start(endTimeStamp - currTimeStamp);
                    remain_time_ll.setVisibility(View.VISIBLE);
                    remain_time_tv.setVisibility(View.GONE);
                }else {
                    remain_time_tv.setText(result);
                    remain_time_tv.setVisibility(View.VISIBLE);
                    remain_time_ll.setVisibility(View.GONE);
                }
            }
        };
        //添加自定义分割线
        DividerItemDecoration divider = new DividerItemDecoration(mActivity,DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(mActivity,R.drawable.layout_divider_item_decoration));
        recycler_view.addItemDecoration(divider);
        recycler_view.setLayoutManager(new LinearLayoutManager(mActivity));
        recycler_view.setAdapter(commonAdapter);
        commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {

            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        refresh_layout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                loadMoreData();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                loadData();
            }
        });
    }

    public void loadData() {
        currPage = 1;
        addDisposableIoMain(couponService.getAllSpellingGroupCouponList(currPage, Constant.PAGE_SIZE,category_id), new DefaultConsumer<List<SpellingGroupCouponBean>>(mApplication) {
            @Override
            public void operateError(String message) {
                super.operateError(message);
                helper.showError("获取数据异常", "");
                refresh_layout.finishRefresh();
            }

            @Override
            public void operateSuccess(BaseResult<List<SpellingGroupCouponBean>> result) {
                dataList.clear();
                if(result.getData().size()<=0){
                    helper.showEmpty();
                }else {
                    dataList.addAll(result.getData());
                    commonAdapter.notifyDataSetChanged();
                    refresh_layout.finishRefresh();
                    helper.showContent();
                    if (result.getData().size()<Constant.PAGE_SIZE){
                        refresh_layout.setEnableLoadMore(false);
                    }else {
                        refresh_layout.setEnableLoadMore(true);
                    }
                }
            }
        },new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                helper.showEmpty();
                refresh_layout.finishRefresh();
            }
        });
    }

    /**
     * 上拉加载更多数据
     */
    public void loadMoreData() {
        currPage++;
        addDisposableIoMain(couponService.getAllSpellingGroupCouponList(currPage,Constant.PAGE_SIZE,category_id), new DefaultConsumer<List<SpellingGroupCouponBean>>(mApplication) {

            @Override
            public void operateSuccess(BaseResult<List<SpellingGroupCouponBean>> baseBean) {
                if (baseBean.getData() != null && baseBean.getData().size() > 0) {
                    dataList.addAll(baseBean.getData());
                    if (baseBean.getData().size() <= Constant.PAGE_SIZE) {
                        noMoreData = true;
                    }
                } else {
                    noMoreData = true;
                }
                commonAdapter.notifyDataSetChanged();
                // 没有更多数据了
                if (noMoreData) {
                    refresh_layout.finishLoadMoreWithNoMoreData();
                } else {
                    refresh_layout.finishLoadMore();
                }
            }
        });
    }
}
